package com.seestech.sell.service;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @description  验证码
 * Created by idiot on 2017/3/9.
 */
@Service
public class KaptchaService {
    private static Logger logger = LoggerFactory.getLogger(KaptchaService.class);

    @Resource
    private DefaultKaptcha captchaProducer;

    /**
     * @description  验证码
     * @param response
     * @param session
     * @param key       存入session的值
     * @throws IOException
     */
    public void createImage(HttpServletResponse response, HttpSession session, String key) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        logger.info("存储验证码===>");
        session.setAttribute(key,capText);//验证码存放到session中
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
